package com.breeze.blockchain.service.impl;

import static com.breeze.blockchain.common.exception.BizErrorCode.ASSIGN_PERMISSION_ERROR;
import static com.breeze.blockchain.mybatis.entity.table.PermissionTable.PERMISSION;
import static com.breeze.blockchain.mybatis.entity.table.RolePermissionTable.ROLE_PERMISSION;

import cn.hutool.core.collection.CollUtil;
import com.breeze.blockchain.controller.admin.vo.PermissionResourceVO;
import com.breeze.blockchain.mybatis.entity.PermissionDo;
import com.breeze.blockchain.mybatis.entity.RolePermissionDo;
import com.breeze.blockchain.mybatis.mapper.RolePermissionMapper;
import com.breeze.blockchain.service.AdminService;
import com.breeze.blockchain.service.PermissionService;
import com.breeze.blockchain.service.RolePermissionService;
import com.breeze.blockchain.service.RoleService;
import com.breeze.components.core.util.id.IdAssembler;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 角色权限关联表 服务层实现。
 *
 * @author breeze
 * @since 2024-05-11 23:21:51
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermissionDo>
    implements RolePermissionService {

  @Resource AdminService adminService;
  @Resource RoleService roleService;
  @Resource PermissionService permissionService;

  @Transactional(rollbackFor = Throwable.class)
  @Override
  public void assignPermission(Long roleId, List<Long> permissionIds) {
    var role = roleService.getExistRoleById(roleId);
    // 先删后加
    remove(query().where(ROLE_PERMISSION.ROLE_ID.eq(roleId)));
    // 空的话就只删除
    if (CollUtil.isEmpty(permissionIds)) {
      return;
    }
    var rolePermissions = RolePermissionDo.from(role, permissionIds);
    ASSIGN_PERMISSION_ERROR.isTrue(this.saveBatch(rolePermissions));
  }

  @Override
  public PermissionResourceVO getUserPermissionResource(Long adminId) {
    var vo = new PermissionResourceVO();
    var admin = adminService.getById(adminId);
    // 用户没权限返回空
    if (Objects.isNull(admin) || Objects.isNull(admin.getRoleId())) {
      return vo;
    }
    // 角色id查权限
    var rolePermissions = queryChain().where(ROLE_PERMISSION.ROLE_ID.eq(admin.getRoleId())).list();
    if (CollUtil.isEmpty(rolePermissions)) {
      return vo;
    }
    // 查权限资源
    var permissionIds =
        IdAssembler.assembleIdSet(rolePermissions, RolePermissionDo::getPermissionId);
    var permissions = permissionService.queryChain().where(PERMISSION.ID.in(permissionIds)).list();
    if (CollUtil.isEmpty(permissions)) {
      return vo;
    }
    var collect =
        permissions.stream().collect(Collectors.groupingBy(PermissionDo::getResourceType));
    return vo.fullData(collect);
  }
}
